/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.test.dao.impl;


import com.test.dao.IBaseDao;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.*;

/**
 *
 * @author think
 */
public class BaseDaoImpl<T> implements IBaseDao<T> {

	@Autowired
	private SessionFactory sessionFactory;

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public <PK extends Serializable> T load(Class<T> model, PK id) {
		return getSession().load(model, id);
	}

	public <PK extends Serializable> T get(Class<T> model, PK id) {
		return getSession().get(model, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll(Class<T> model, List<String[]> orderInfos) {
		Criteria criteria = getSession().createCriteria(model);
		for (String[] orderInfo : orderInfos) {
			if ("asc".equals(orderInfo[1])) {
				criteria.addOrder(Order.asc(orderInfo[0]));
			} else if ("desc".equals(orderInfo[1])) {
				criteria.addOrder(Order.desc(orderInfo[0]));
			}
		}
		return criteria.list();
	}
	protected void setHQLParameters(Query query, Map<String, Object> paramlist) {
		if (paramlist != null) {
			Set<Map.Entry<String, Object>> set = paramlist.entrySet();
			for (Iterator<Map.Entry<String, Object>> it = set.iterator(); it
					.hasNext();) {
				Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it
						.next();
				String key = entry.getKey();
				Object value = entry.getValue();
				if (value instanceof Collection) {
					query.setParameterList(key, (Collection) value);
				} else {
					query.setParameter(key, value);
				}
			}
		}
	}
	@SuppressWarnings("unchecked")
	public List<T> getAll(Class<T> model, String sortName, String sortType) {
		Criteria criteria = getSession().createCriteria(model);
		if ("asc".equals(sortType)) {
			criteria.addOrder(Order.asc(sortName));
		} else if ("desc".equals(sortType)) {
			criteria.addOrder(Order.desc(sortName));
		}
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll(Class<T> model) {
		Criteria criteria = getSession().createCriteria(model);
		return criteria.list();
	}

	public Serializable save(T model) {
		return getSession().save(model);
	}

	public void saveOrUpdate(T model) {
		getSession().saveOrUpdate(model);
	}

	public void update(T model) {
		getSession().update(model);
		getSession().flush();
	}

	public void delete(T model) {
		getSession().delete(model);
		getSession().flush();
	}



	/**
	 * 获取开始条数
	 *
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	private static int getPageStart(int pageNumber, int pageSize) {
		return (pageNumber - 1) * pageSize;
	}




}
